package com.quarter.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.quarter.action.LoginAction;
import com.quarter.dao.ChangePwDao;
import com.quarter.db.DBConnect;
import com.quarter.db.Data;
import com.quarter.vo.User;

public class ChangePwDaoImpl implements ChangePwDao{
	public int validateChange(User user) throws Exception
	{
		String type="student";
		String id="sid";
		Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);
		user.setUid(session.get("uid").toString());
		user.setIdentity(session.get("identity").toString());
		if(user.getIdentity().equals("admin"))
		{
			type="administer";id="aid";
		}
		else if(user.getIdentity().equals("student"))
		{	
			type="student";id="sid";
		}
		else
		{
			type="enterprise_instructor";id="iid";
		}
		
		int flag = 0;
		
		String sql = "select * from "+type+" where "+id+"='"+user.getUid()+"'";
		DBConnect dbc = new DBConnect();
		try{
			ResultSet rs= dbc.getRs(sql);
			if(rs.next()){
				if(rs.getString("password").equals(user.getPassword())){
					flag = 1;
				}
			}
			rs.close();
		}catch(SQLException e){
			System.out.println(e.getMessage());
		}finally{
			dbc.close();
		}
		return flag;
	}
		

	public int changePassword(User user) throws Exception {
		// TODO Auto-generated method stub
		int flag=0;
		String type="student";
		String id="sid";
		Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);
		user.setUid(session.get("uid").toString());
		user.setIdentity(session.get("identity").toString());
		if(user.getIdentity().equals("admin"))
		{
			type="administer";id="aid";
		}
		else if(user.getIdentity().equals("student"))
		{	
			type="student";id="sid";
		}
		else
		{
			type="enterprise_instructor";id="iid";
		}
		
		String sql = "update "+type+" set password='"+user.getNewpassword1()+"' where "+id+"='"+user.getUid()+"'";
		Data data = new Data();
		
		try{
			flag = data.update(sql);
			
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return flag;
	}

}
